﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Aioms.Controllers;
using Aioms.Models;
using EasyQuartz;
using Furion;
using Furion.DatabaseAccessor;
using Masuit.Tools;
using Quartz;
using SqlSugar;
using SqlSugar.Extensions;

namespace Aioms.Cron
{
    //[TriggerCron("0/1 * * * * ? *")]
    [TriggerCron("0 0/2 * * * ? *")]
    [DisallowConcurrentExecution]
    public class MessageJob : IJob
    {
        private readonly ISqlSugarClient db; // 核心对象：拥有完整的SqlSugar全部功能
        public MessageJob() {
            this.db = new SqlSugarClient(new ConnectionConfig
            {
                ConnectionString = App.Configuration["ConnectionStrings:Default"],
                IsAutoCloseConnection = true,
                InitKeyType = InitKeyType.Attribute//从特性读取主键自增信息
            });
            //处理日志事务
            db.Aop.OnLogExecuting = (sql, pars) =>
            {
                Console.WriteLine(sql);
                Console.WriteLine(string.Join(",", pars?.Select(it => it.ParameterName + ":" + it.Value)));
                Console.WriteLine();
            };
        }
        public async Task Execute(IJobExecutionContext context)
        {
            Console.WriteLine($"{DateTime.Now} 消息任务开始执行");
            List<TpWorkOrder> workorders = await db.Queryable<TpWorkOrder>().ToListAsync();
            foreach (var workorder in workorders)
            {
                // 先去消息里查看该工单有没有发送通知，没有的话发送通知
                int message_count = await db.Queryable<Message>().Where(msg => msg.Eid == workorder.Eid)
                    .Where(msg => msg.Source == "工单")
                    .Where(msg => msg.RefId == workorder.Id)
                    .CountAsync();
                if (message_count == 0 && (workorder.BeginTime - DateTime.Now).TotalMinutes <= 30 && !string.IsNullOrEmpty(workorder.Epids))
                {
                    string[] epids = workorder.Epids.Split(",", StringSplitOptions.RemoveEmptyEntries);
                    foreach (var epid in epids)
                    {
                        await db.Insertable<Message>(new Message { Eid = workorder.Eid, Name = workorder.Name, Qian = "即将开始，", Hou = "请及时查看！", Epid = epid.ToInt32(), Source = "工单", RefId = workorder.Id, Type = "工单", Isread = 0 }).ExecuteCommandAsync();
                    }
                }
            }
        }
    }
}
